package studentdemo.ui;

import studentdemo.modul.Teacher;
import studentdemo.server.TeacherService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class TeacherPanel extends JPanel {
    private TeacherService teacherService = new TeacherService();
    private JTable table;
    private DefaultTableModel tableModel;
    private JTextField searchIdField, searchNameField;
    private JButton searchBtn, addBtn, editBtn, deleteBtn, prevBtn, nextBtn, refreshBtn;
    private int currentPage = 1;
    private final int pageSize = 10;
    private int totalPage = 1;

    public TeacherPanel() {
        setLayout(new BorderLayout());
        // 顶部查询区
        JPanel searchPanel = new JPanel();
        searchPanel.add(new JLabel("工号:"));
        searchIdField = new JTextField(8);
        searchPanel.add(searchIdField);
        searchPanel.add(new JLabel("姓名:"));
        searchNameField = new JTextField(8);
        searchPanel.add(searchNameField);
        searchBtn = new JButton("查询");
        searchPanel.add(searchBtn);
        refreshBtn = new JButton("刷新");
        searchPanel.add(refreshBtn);
        add(searchPanel, BorderLayout.NORTH);

        // 表格区
        String[] columns = {"工号", "姓名", "性别", "年龄", "职称", "电话"};
        tableModel = new DefaultTableModel(columns, 0) {
            public boolean isCellEditable(int row, int column) { return false; }
        };
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // 底部操作区
        JPanel opPanel = new JPanel();
        addBtn = new JButton("新增");
        editBtn = new JButton("修改");
        deleteBtn = new JButton("删除");
        prevBtn = new JButton("上一页");
        nextBtn = new JButton("下一页");
        opPanel.add(addBtn);
        opPanel.add(editBtn);
        opPanel.add(deleteBtn);
        opPanel.add(prevBtn);
        opPanel.add(nextBtn);
        add(opPanel, BorderLayout.SOUTH);

        // 事件绑定
        searchBtn.addActionListener(e -> searchAction());
        refreshBtn.addActionListener(e -> loadTable(currentPage));
        addBtn.addActionListener(e -> showTeacherDialog(null));
        editBtn.addActionListener(e -> editTeacherAction());
        deleteBtn.addActionListener(e -> deleteTeacherAction());
        prevBtn.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                loadTable(currentPage);
            }
        });
        nextBtn.addActionListener(e -> {
            if (currentPage < totalPage) {
                currentPage++;
                loadTable(currentPage);
            }
        });

        loadTable(1);
    }

    private void loadTable(int page) {
        tableModel.setRowCount(0);
        int count = teacherService.getTeacherCount();
        totalPage = (int) Math.ceil(count * 1.0 / pageSize);
        if (totalPage == 0) totalPage = 1;
        List<Teacher> list = teacherService.getTeachersByPage(page, pageSize);
        for (Teacher t : list) {
            tableModel.addRow(new Object[]{
                    t.getTno(), t.getTname(), t.getTsex(), t.getTage(), t.getTtitle(), t.getTphone()
            });
        }
    }

    private void searchAction() {
        String tno = searchIdField.getText().trim();
        String name = searchNameField.getText().trim();
        tableModel.setRowCount(0);
        if (!tno.isEmpty()) {
            Teacher t = teacherService.getTeacherById(tno);
            if (t != null) {
                tableModel.addRow(new Object[]{
                        t.getTno(), t.getTname(), t.getTsex(), t.getTage(), t.getTtitle(), t.getTphone()
                });
            } else {
                JOptionPane.showMessageDialog(this, "未找到该工号教师");
            }
        } else if (!name.isEmpty()) {
            List<Teacher> list = teacherService.getTeachersByName(name);
            for (Teacher t : list) {
                tableModel.addRow(new Object[]{
                        t.getTno(), t.getTname(), t.getTsex(), t.getTage(), t.getTtitle(), t.getTphone()
                });
            }
        } else {
            loadTable(1);
        }
    }

    private void showTeacherDialog(Teacher teacher) {
        JTextField tnoField = new JTextField();
        JTextField tnameField = new JTextField();
        JComboBox<String> tsexBox = new JComboBox<>(new String[]{"男", "女"});
        JTextField tageField = new JTextField();
        JTextField ttitleField = new JTextField();
        JTextField tphoneField = new JTextField();

        if (teacher != null) {
            tnoField.setText(teacher.getTno());
            tnoField.setEditable(false);
            tnameField.setText(teacher.getTname());
            tsexBox.setSelectedItem(teacher.getTsex());
            tageField.setText(String.valueOf(teacher.getTage()));
            ttitleField.setText(teacher.getTtitle());
            tphoneField.setText(teacher.getTphone());
        }

        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("工号:")); panel.add(tnoField);
        panel.add(new JLabel("姓名:")); panel.add(tnameField);
        panel.add(new JLabel("性别:")); panel.add(tsexBox);
        panel.add(new JLabel("年龄:")); panel.add(tageField);
        panel.add(new JLabel("职称:")); panel.add(ttitleField);
        panel.add(new JLabel("电话:")); panel.add(tphoneField);

        int result = JOptionPane.showConfirmDialog(this, panel, teacher == null ? "新增教师" : "修改教师", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                String tno = tnoField.getText().trim();
                String tname = tnameField.getText().trim();
                String tsex = (String) tsexBox.getSelectedItem();
                int tage = Integer.parseInt(tageField.getText().trim());
                String ttitle = ttitleField.getText().trim();
                String tphone = tphoneField.getText().trim();
                Teacher t = new Teacher(tno, tname, tsex, tage, ttitle, tphone);
                boolean success;
                if (teacher == null) {
                    success = teacherService.addTeacher(t);
                } else {
                    success = teacherService.updateTeacher(t);
                }
                if (success) {
                    JOptionPane.showMessageDialog(this, "操作成功");
                    loadTable(currentPage);
                } else {
                    JOptionPane.showMessageDialog(this, "操作失败");
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "输入有误: " + ex.getMessage());
            }
        }
    }

    private void editTeacherAction() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一行");
            return;
        }
        String tno = (String) tableModel.getValueAt(row, 0);
        Teacher t = teacherService.getTeacherById(tno);
        if (t != null) {
            showTeacherDialog(t);
        }
    }

    private void deleteTeacherAction() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一行");
            return;
        }
        String tno = (String) tableModel.getValueAt(row, 0);
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除工号为" + tno + "的教师吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            boolean success = teacherService.deleteTeacher(tno);
            if (success) {
                JOptionPane.showMessageDialog(this, "删除成功");
                loadTable(currentPage);
            } else {
                JOptionPane.showMessageDialog(this, "删除失败");
            }
        }
    }
} 